package com.tanhua.manager.job;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.AnalysisByDay;
import com.tanhua.mapper.AnalysisByDayMapper;
import com.tanhua.mapper.LogMapper;
import com.tanhua.util.ComputeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AnalysisJob {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Scheduled(cron = "0 0 0/1 * * ?")  // 每间隔一个小时执行一次
    public void logToAnalysis() { // 日志生成统计分析

        // 今天
        Date date = new Date();
        String today = DateUtil.format(date, "yyyy-MM-dd");
        // 昨天
        String yesterday = ComputeUtil.offsetDay(date, -1);

        System.out.println("开启日志分析：" + today);
        // 1、查询日志表
        Integer registerNum = logMapper.selectNumByTypeAndTime("0102", today); // 今日注册
        Integer loginNum = logMapper.selectNumByTypeAndTime("0101", today); // 今日登录
        Integer activeNum = logMapper.selectNumByTime(today); // 今日活跃
        Integer retentionNum = logMapper.findNumByRetention(today, yesterday); // 次日留存

        // 2、保存分析表
        // 2.1 先查统计分析表
        QueryWrapper<AnalysisByDay> qw = new QueryWrapper<>();
        qw.eq("record_date", today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(qw);

        // 2.2 判断
        if (analysisByDay == null) { // 新增
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(date);
            analysisByDay.setNumRegistered(registerNum);
            analysisByDay.setNumLogin(loginNum);
            analysisByDay.setNumActive(activeNum);
            analysisByDay.setNumRetention1d(retentionNum);
            analysisByDayMapper.insert(analysisByDay);
        } else { // 更新
            analysisByDay.setNumRegistered(registerNum);
            analysisByDay.setNumLogin(loginNum);
            analysisByDay.setNumActive(activeNum);
            analysisByDay.setNumRetention1d(retentionNum);
            analysisByDayMapper.updateById(analysisByDay);
        }

        System.out.println("结束日志分析");
    }
}
